package org.easy.excel.support.handler;

import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.poi.ss.usermodel.*;
import org.common.constant.MagicValue;
import org.easy.excel.support.config.AnnotationExcelConfig;
import org.easy.excel.support.config.entity.TitleConfig;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

/**
 * 行数据格式处理
 *
 * @author 李坤
 * @date 2022/4/25 22:14
 */
public class AnnotationHeadRowWriteHandler extends AbstractRowWriteHandler {

    /**
     * 默认的字体样式配置（黑体、11）
     */
    private final WriteFont defaultWriteFont4HT_11 = new WriteFont();

    /**
     * 默认的字体样式配置（楷体、11）
     */
    private final WriteFont defaultWriteFont4KT_11 = new WriteFont();

    /**
     * 默认的单元格样式配置
     */
    private final WriteCellStyle defaultWriteCellStyle = new WriteCellStyle();

    /**
     * 默认的单元格样式容器
     */
    private final Map<String, CellStyle> cellStyleContainer = new HashMap<>(4);

    /**
     * 默认的单元格字体样式容器
     */
    private final Map<String, WriteFont> writeFontContainer = new HashMap<>(4);

    /**
     * 默认的WriteCellStyle容器
     */
    private final Map<String, WriteCellStyle> writeCellStyleContainer = new HashMap<>(4);

    /**
     * 最终导出的数据条数
     */
    private Integer dataLineSize;

    /**
     * Excel导出标题配置
     */
    private final TitleConfig titleConfig;

    {
        defaultWriteFont4HT_11.setFontName("黑体");
        defaultWriteFont4HT_11.setFontHeightInPoints((short) 11);

        defaultWriteFont4KT_11.setFontName("楷体");
        defaultWriteFont4KT_11.setFontHeightInPoints((short) 11);

        writeFontContainer.put("HT_11", defaultWriteFont4HT_11);
        writeFontContainer.put("ST_11", defaultWriteFont4KT_11);

        final WriteFont writeFont = new WriteFont();
        writeFont.setFontHeightInPoints((short) 18);
        writeFont.setFontName("黑体");
        writeFont.setBold(true);

        // 设置字体配置
        defaultWriteCellStyle.setWriteFont(writeFont);
        // 设置背景颜色
        defaultWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.index);
    }

    /**
     * 默认的构造函数
     *
     * @param dataLineSize          导出数据的行数
     * @param annotationExcelConfig Excel导出配置类
     */
    public AnnotationHeadRowWriteHandler(Integer dataLineSize, AnnotationExcelConfig annotationExcelConfig) {
        this.dataLineSize = dataLineSize;
        this.titleConfig = annotationExcelConfig.getTitleConfig();
    }

    /**
     * 默认的构造函数
     *
     * @param dataLineSize 导出数据的行数
     * @param titleConfig  导出的标题配置信息
     */
    public AnnotationHeadRowWriteHandler(Integer dataLineSize, TitleConfig titleConfig) {
        this.titleConfig = titleConfig;
        this.dataLineSize = dataLineSize;
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                Row row, Integer relativeRowIndex, Boolean isHead) {
        final Workbook workbook = writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook();

        if (isHead) {
            if (relativeRowIndex < titleConfig.getTopTitleColumns()) {
                // 处理顶级标题的样式
                row.getCell(0).setCellStyle(StyleUtil.buildHeadCellStyle(workbook, defaultWriteCellStyle));
            } else if (relativeRowIndex < titleConfig.getSecondaryTitleColumns()) {
                // 处理 AbstractAnnotationExcelConfig 子类设置的自定义标题（次级标题）
                for (int index = 0; index < row.getLastCellNum(); index++) {
                    final WriteCellStyle writeCellStyle = new WriteCellStyle();
                    writeCellStyle.setFillForegroundColor(IndexedColors.WHITE.index);
                    writeCellStyle.setWriteFont(defaultWriteFont4HT_11);

                    if (index == 0) {
                        writeCellStyle.setRightBorderColor(IndexedColors.WHITE.index);
                        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
                    } else if (index == row.getLastCellNum() - 1) {
                        writeCellStyle.setLeftBorderColor(IndexedColors.WHITE.index);
                        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.RIGHT);
                    } else {
                        writeCellStyle.setLeftBorderColor(IndexedColors.WHITE.index);
                        writeCellStyle.setRightBorderColor(IndexedColors.WHITE.index);
                    }
                    row.getCell(index).setCellStyle(StyleUtil.buildHeadCellStyle(workbook, writeCellStyle));
                }
            } else if (relativeRowIndex < titleConfig.getFieldTitleColumns()) {
                for (Iterator<Cell> iterator = row.cellIterator(); iterator.hasNext(); ) {
                    final WriteCellStyle writeCellStyle = new WriteCellStyle();
                    writeCellStyle.setWriteFont(defaultWriteFont4HT_11);
                    writeCellStyle.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.index);

                    iterator.next().setCellStyle(StyleUtil.buildHeadCellStyle(workbook, writeCellStyle));
                }
            } else if (relativeRowIndex < titleConfig.getLowestLevelTitleColumns()) {
                // TODO 待处理
            }
        } else {
            final int size = dataLineSize - 1;
            final short lastCellNum = row.getLastCellNum();

            if (relativeRowIndex != size) {
                for (int i = 0; i < lastCellNum; i++) {
                    // 序号列居中，其他列居左
                    final HorizontalAlignment alignment = (i == 0) ? HorizontalAlignment.CENTER : HorizontalAlignment.LEFT;
                    row.getCell(i).setCellStyle(getCellStyle(workbook, null, alignment));
                }
            } else {
                final WriteCellStyle writeCellStyle = new WriteCellStyle();

                writeCellStyle.setWriteFont(defaultWriteFont4KT_11);
                writeCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());

                for (int i = 0; i < lastCellNum; i++) {
                    // 序号列居中，其他列居左
                    writeCellStyle.setHorizontalAlignment((i == 0) ? HorizontalAlignment.CENTER : HorizontalAlignment.LEFT);
                    // 合计行设置背景色，当支持设置合计行的时候
                    row.getCell(i).setCellStyle(StyleUtil.buildHeadCellStyle(workbook, writeCellStyle));
                }
            }
        }
    }


    /*-------------------------------------------------private methods------------------------------------------------*/


    /**
     * 根据给定的数据获取 单元格样式-{@link CellStyle} 对象
     *
     * @param workbook        工作簿
     * @param foregroundColor 颜色标识
     * @param alignment       数据位置
     *
     * @return 单元格样式对象
     */
    private CellStyle getCellStyle(Workbook workbook, Short foregroundColor, HorizontalAlignment alignment) {
        final String cellStyleFlag = (foregroundColor + MagicValue.JOINER + alignment).intern();

        CellStyle cellStyle;
        if (Objects.isNull(cellStyle = cellStyleContainer.get(cellStyleFlag))) {
            final WriteCellStyle writeCellStyle = new WriteCellStyle();
            writeCellStyle.setWriteFont(defaultWriteFont4KT_11);
            if (Objects.nonNull(alignment)) {
                writeCellStyle.setHorizontalAlignment(alignment);
            }
            if (Objects.nonNull(foregroundColor)) {
                writeCellStyle.setFillForegroundColor(foregroundColor);
            }

            cellStyle = StyleUtil.buildContentCellStyle(workbook, writeCellStyle);
            cellStyleContainer.put(cellStyleFlag, cellStyle);
        }
        return cellStyle;
    }

}
